<script setup>
import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5'
import { useMessage } from 'naive-ui';
import { useModalStore, useDataStore } from '@/store';
import { inject } from 'vue';

const ModalBodyStyle = {
	'width': '90vw',
	'height': '75vh',
	'background-color': '#fff',
	'border-radius': '5px',
};

const UploadTriggerStyle = {
	'width': '100%',
	'height': '100%',
	'display': 'flex',
	'flex-direction': 'column',
	'justify-content': 'center',
	'align-items': 'center'
};

const UploadDraggerCompontStyle = {
	...UploadTriggerStyle,
	'border': '1px dashed #409eff',
	'border-radius': '5px',
};

const message = useMessage();
const modalStore = useModalStore();
const dataStore = useDataStore();

// 通过 provide/inject 获取 coordinateCanvas 实例
const coordinateCanvasRef = inject('coordinateCanvasRef');

const customRequest = ({
	file,
	// data,
	// headers,
	// withCredentials,
	// action,
	// onFinish,
	// onError,
	// onProgress
}) => {
	try {
		const reader = new FileReader();

		reader.onload = (e) => {
			const jsonData = JSON.parse(e.target.result);

			if (jsonData) {
				// 直接更新 store
				dataStore.setRoomList(jsonData);
				
				// 直接调用 canvas 方法
				if (coordinateCanvasRef?.value) {
					coordinateCanvasRef.value.updateEchartsData(jsonData);
				}
				
				message.success('数据导入成功');
			} else {
				message.error('文件格式不正确');
			}

			modalStore.closeImportModal();
		};

		reader.readAsText(file.file);
	} catch (error) {
		message.error('文件解析错误，请检查文件格式');
	}
};

</script>

<template>
	<n-modal class="import-data-modal" v-model:show="modalStore.showImportModal" block-scroll close-on-esc :style="ModalBodyStyle">
		<n-upload :max="1" default-upload accept=".json" :custom-request="customRequest"
			:trigger-style="UploadDraggerCompontStyle">
			<n-upload-dragger :style="UploadDraggerCompontStyle">
				<div>
					<n-icon size="70" :depth="3">
						<ArchiveIcon />
					</n-icon>
				</div>
				<n-text style="font-size: 18px">
					点击或者拖动文件到该区域来上传
				</n-text>
				<n-p depth="4" style="margin: 8px 0 0 0">
					<span>支持格式：</span>
					<span style="color: #409eff">.json</span>
				</n-p>
			</n-upload-dragger>
		</n-upload>
	</n-modal>

</template>

<style lang="scss" scoped>
.import-data-modal {
	width: 400px;
}

.upload-icon {
	width: 48px;
	height: 48px;
	background-color: #eee;
	background: url('../../assets/svg/upload.png') no-repeat center;
}
</style>